package com.ptswitch.material.pages.contract;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.project.AppRuntimeException;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.ContractService;
import com.ptswitch.material.service.ContractSupplierService;
import com.ptswitch.material.service.UserService;
import com.ptswitch.material.util.ContractUtil;
import com.ptswitch.material.util.HlogConstants;
import com.ptswitch.material.util.security.PermissionUtil;

public class EditContract extends PageBase {

    @Inject
    private UserService userSer;
    @Inject
    private ContractService contractSer;
    @Inject
    private ContractSupplierService contractSupplierSer;
    @Property
    private Contract contract;
    //
    @InjectPage
    private ViewContract viewContract;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id) {
        contract = contractSer.findById(id);
        checkPermitted(PermissionUtil.ContractEdit);
        if (!Contract.Status_UnOk.equals(contract.getStatus())) {
            throw AppRuntimeException.error("只有未完成的合同才能被修改");
        }
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return contract.getId();
    }

    @OnEvent(value = EventConstants.PROVIDE_COMPLETIONS, component = "c_supplier")
    List<String> provideCompletionsForContractSupplierName(String partial) {
        return contractSupplierSer.findAllName();
    }

    @OnEvent(value = EventConstants.SUCCESS)
    Object updateContract() {
        checkPermitted(PermissionUtil.ContractEdit);
        if (!Contract.Status_UnOk.equals(contract.getStatus())) {
            throw AppRuntimeException.error("只有未完成的合同才能被修改");
        }
        contractSer.save(contract);
        //hlog
        hlog(HlogConstants.updateContract, contract);
        return viewContract.withInit(contract.getId());
    }

    @Override
    protected List<Role> appendRoleToVisitor(Uzer visitor) {
        return ContractUtil.appendThisRole(contract, visitor);
    }
}
